package dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class BaseDao {
    //数据库驱动字符串
    static String driver;
    //连接 URL 字符串
    static String url;
    //数据库用户名
    static String username;
    //用户密码
    static String password;

    Connection conn = null;

    static{
        init();
    }

    public static void init(){
        Properties properties = new Properties();
        String file = "database.properties";
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(file);
        try{
            properties.load(is);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            Class.forName(driver);
        }catch (IOException e){
            e.printStackTrace();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    public Connection getConnection(){
        try{
            if(conn == null || conn.isClosed()){
                conn = DriverManager.getConnection(url,username,password);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return conn;
    }

    public void getClose(Connection conn, PreparedStatement ps, ResultSet rs){
        try{
            if(conn != null){
                conn.close();
            }
            if(ps != null){
                ps.close();
            }
            if(rs != null){
                rs.close();
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }

    protected ResultSet executeQuery(String sql,Object... params){
        conn = this.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try{
            pstmt = conn.prepareStatement(sql);
            for(int i = 0;i<params.length;i++){
                pstmt.setObject(i + 1,params[i]);
            }
            rs = pstmt.executeQuery();
        }catch (SQLException e){
            e.printStackTrace();
        }
        return rs;
    }
}
